package cn.tenmg.flink.jobs.launcher.utils;

import java.io.IOException;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

public class HttpClientUtils {

	private static String charset = "UTF-8";

	private static final CloseableHttpClient client;

	private static final RequestConfig requestConfig;

	static {
		PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
		connectionManager.setMaxTotal(200);
		connectionManager.setDefaultMaxPerRoute(60);
		client = HttpClients.custom().setConnectionManager(connectionManager).build();
		requestConfig = RequestConfig.custom().setConnectionRequestTimeout(30000).setConnectTimeout(10000).build();
	}

	public static String get(String url) throws Exception {
		HttpGet get = new HttpGet((url.indexOf('?') >= 0 ? url + "&_=" : url + "?_=") + System.currentTimeMillis());
		get.setHeader("Accept", "application/json");
		get.setHeader("Connection", "close");
		get.setConfig(requestConfig);
		CloseableHttpResponse response = null;
		String result = null;
		try {
			response = client.execute(get);
			result = EntityUtils.toString(response.getEntity(), charset);
			get.abort();
		} catch (Exception e) {
			throw e;
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
				}
			}
			response = null;
			get = null;
		}
		return result;
	}

	public static String put(String url, String data) throws Exception {
		HttpPut put = new HttpPut(url);
		put.setHeader("Accept", "application/json");
		put.setHeader("Connection", "close");
		put.setConfig(requestConfig);
		if (data != null) {
			put.setEntity(new StringEntity(data, ContentType.create("application/json", charset)));
		}
		CloseableHttpResponse response = null;
		String result = null;
		try {
			response = client.execute(put);
			result = EntityUtils.toString(response.getEntity(), charset);
			put.abort();
		} catch (Exception e) {
			throw e;
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
				}
			}
			response = null;
			put = null;
		}
		return result;
	}

}
